package com.dandelion.api.config;

import com.dandelion.api.manager.UserAccountManager;
import com.dandelion.common.domain.AccessToken;
import com.dandelion.common.http.HttpContext;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpContextInterceptor implements HandlerInterceptor {
    private static final String USER_TOKEN_KEY = "token";
    private UserAccountManager accountManager;

    public HttpContextInterceptor(UserAccountManager accountManager) {
        this.accountManager = accountManager;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        HttpContext ctx = HttpContext.current();
        String userToken = request.getParameter(USER_TOKEN_KEY);
        if (StringUtils.isBlank(userToken)) {
            userToken = getUserTokenFromCookies(request);
        }

        //set user token and userId
        if (StringUtils.isNotBlank(userToken)) {
            AccessToken token = accountManager.getUserAccessToken(userToken);
            if (token != null && token.getUserId() != null && token.getUserId() > 0L) {
                ctx.setUserId(token.getUserId());
                ctx.setUserToken(userToken);
            }
        }
        return true;
    }


    private static String getUserTokenFromCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (ArrayUtils.isEmpty(cookies)) {
            return null;
        }

        for (Cookie c : cookies) {
            if (USER_TOKEN_KEY.endsWith(c.getName())) {
                return c.getValue();
            }
        }

        return null;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HttpContext.destroy();
    }
}